$(document).ready(function() {
	$('#userRole').datagrid({
		data :null
	});
		
	$('#reloadList').linkbutton('disable');
	
	$("#targetUser").combobox({
		onSelect : function(record) {
			loadGridData(record.id);
			$('#reloadList').linkbutton('enable');
		}
	});
});


function loadGridData(username) {
	if (username == undefined)
		return;
//	$.getJSON('listRole.htm?userId=' + username, function(resData) {
//		$('#userRole').datagrid({
//			data : resData
//		});
//	});
	
	$.getJSON('listRole.htm?userId=' + username, function(resData) {
		$('#userRole').datagrid({
			data : resData
		});
	})
	.done(function(data){
		var rows = $('#userRole').datagrid('getRows');
		 for (var i = 0; i < rows.length; ++i) {
             if (rows[i]['permitted'] == true) 
            	 $('#userRole').datagrid('checkRow', i);
         }
	});
}

function reloadList(){
	loadGridData($("#targetUser").combobox('getValue'));
}

function saveList(){
         var roles = [];
         var rows = $('#userRole').datagrid('getSelections');
         for(var i=0;i<rows.length;i++){
        	 roles.push(rows[i].name);
         }
         var data = {};
         
         data["roles"]=roles.join(':');
         data["targetUser"]=$("#targetUser").combobox('getValue');
         
         
             $.postJSON("UpdateRole.htm", data, function(result) {
	     		if (result.success) {
	     			showMessager("Info", result.message);
	     			loadGridData('Pending');
	     		} else {
	     			showMessager("Exception", result.message);
	     		}
	     	}, function(xhr, ajaxOptions, thrownError) {
	     		showMessager("Exception", thrownError);
	     	});
         
}
